package com.p2p.auth.service.specification;


import com.p2p.auth.domain.dto.visitor.VisitorQueryDTO;
import com.p2p.auth.domain.entity.Visitor;
import org.hibernate.annotations.common.util.StringHelper;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author Evan
 * @date 2018/2/12
 */
public class VisitorSpecification {
    public static Specification<Visitor> buildFromDTO(VisitorQueryDTO dto){
        return (root, query, builder) -> {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfmat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            ArrayList<Predicate> list = new ArrayList<>();

            if (StringHelper.isNotEmpty(dto.getRealName())) {
                list.add(builder.like(root.get("visitorRealName"), "%" + dto.getRealName() + "%"));
            }


            if ( dto.getOnType() != null) {
                list.add(builder.equal(root.get("onType"), dto.getOnType()));
            }

            if (StringHelper.isNotEmpty(dto.getPhoneNum())) {
                list.add(builder.like(root.get("visitorPhoneNum"), "%" + dto.getPhoneNum() + "%"));
            }

            if (StringHelper.isNotEmpty(dto.getRetailerId())) {
                list.add(builder.like(root.get("retailerIds"), "%" + dto.getRetailerId() + "%"));
            }

            if (StringHelper.isNotEmpty(dto.getP2pCompanyId())) {
                list.add(builder.like(root.get("p2pCompanyIds"), "%" + dto.getP2pCompanyId() + "%"));
            }

            if (dto.getDateStart() != null && dto.getDateEnd() != null) {
                list.add(builder.between(root.<Date>get("eventDate"), dto.getDateStart(), dto.getDateEnd()));
            }

            Predicate[] predicates = new Predicate[list.size()];
            predicates = list.toArray(predicates);
            return builder.and(predicates);
        };
    }
}
